package com.common.web.socket;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CopyOnWriteArraySet;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

import org.springframework.stereotype.Component;

import lombok.extern.slf4j.Slf4j;

@Component
@ServerEndpoint("/connect/{userId}/{terminalType}")
@Slf4j
public class WebSocketServer {
	
	public WebSocketServer() {
		log.debug("WebSocketServer初始化......"+this.getClass().getSimpleName());
	}
	
    // 静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
    private static int onlineCount = 0;
    // concurrent包的线程安全Set，用来存放每个客户端对应的MyWebSocket对象。
    private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>();

    // 与某个客户端的连接会话，需要通过它来给客户端发送数据
    private String userId;
    private List<WebSocketTerminal> webSocketTerminals = new ArrayList<>();;

    /**
     * 连接建立成功调用的方法
     * 
     * @param userId 建立连接的用户ID
     * @param terminalType 建立连接的终端类型 1 移动端 2 pc端 3 其他
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("userId") String userId,
        @PathParam("terminalType") String terminalType) {
        // this.session = session;
        this.userId = userId;
        // webSocketSet.add(this);
        // 加入set中
        // addOnlineCount();
        // 在线数加1
        // log.info("有新连接加入！当前在线人数为" + getOnlineCount());
        try {
            WebSocketTerminal wt = new WebSocketTerminal();
            wt.setSession(session);
            wt.setTerminalType(terminalType);
            Optional<WebSocketServer> wsOptional =
                webSocketSet.stream().filter(a -> a.userId.equals(userId)).findFirst();
            if (wsOptional.isPresent()) {
                WebSocketServer ws = wsOptional.get();
                Optional<WebSocketTerminal> typeOptional =
                    ws.webSocketTerminals.stream().filter(a -> a.getTerminalType().equals(terminalType)).findFirst();
                if (typeOptional.isPresent()) {
                    // 除旧换新
                    ws.webSocketTerminals.remove(typeOptional.get());
                }
                ws.webSocketTerminals.add(wt);
            } else {
                // 初次登录
                this.webSocketTerminals.add(wt);
                webSocketSet.add(this);
            }
            sendMessage("连接成功");
        } catch (IOException e) {
        	log.error("websocket IO异常");
        }
    }

    /*
    Send Message
     */
    @OnMessage
    public String onMessage(@PathParam("userId") String userId, String message) {
    	log.info("[WebSocketServer] Received Message : userId = " + userId + " , message = " + message);
        if (message.equals("&")) {
            return "&";
        } else {
            WebSocketUtils.receive(userId, message);
            return "Got your message (" + message + ").";
        }
    }

    public void sendMessage(String message) throws IOException {
        for (WebSocketTerminal wt : this.webSocketTerminals) {
            wt.getSession().getBasicRemote().sendText(message);
        }
    }

    public void sendMessage(Object message) throws Exception {
        for (WebSocketTerminal wt : this.webSocketTerminals) {
            wt.getSession().getBasicRemote().sendObject(message);
        }
    }

    /**
     * 往指定用户群发通知数量更新消息 *
     */
    public static void sendInfo(String message, List<String> userIds) throws IOException {
        for (WebSocketServer item : webSocketSet) {
            try {
                if (userIds.contains(item.userId)) {
                    item.sendMessage(message);
                }
            } catch (IOException e) {
                continue;
            }
        }
    }

    /**
     * 往指定用户群发通知数量更新消息 *
     */
    public static void sendInfo(Map<String, String> notifyMap) throws IOException {
        Iterator<Map.Entry<String, String>> it = notifyMap.entrySet().iterator();

        try {
            while (it.hasNext()) {
                Map.Entry<String, String> entry = it.next();
                for (WebSocketServer item : webSocketSet) {
                    if (entry.getKey().equals(item.userId)) {
                        // 把未读通知数量推送到已登陆的用户页面
                        item.sendMessage(entry.getValue());
                        it.remove();
                        break;
                    }
                }
            }
        } catch (IOException e) {
        	log.error("批量推送未读通知数量异常：" + e);
        }
    }

    /**
     * 筛选出处于登陆状态的用户
     *
     * @param uids
     * @return
     */
    public static List<String> findLoginUserIds(List<String> uids) {
        List<String> ids = new ArrayList<String>();
        for (WebSocketServer item : webSocketSet) {
            if (uids.contains(item.userId)) {
                ids.add(item.userId);
            }
        }
        return ids;
    }

    /**
     * Error.
     *
     * @param userId
     * @param throwable
     * @param session
     */
    @OnError
    public void onError(@PathParam("userId") String userId, Throwable throwable, Session session) {
    	log.info(
            "[WebSocketServer] Connection Exception : userId = " + userId + " , throwable = " + throwable.getMessage());
        WebSocketUtils.remove(userId);
    }

    /*
    Close Connection
     */
    @OnClose
    public void onClose(@PathParam("userId") String userId, Session session) {
    	log.info("[WebSocketServer] Close Connection : userId = " + userId);
        WebSocketUtils.remove(userId);
    }

}
